package com.wordplat.quickstart.xutils.http.loader;

import com.wordplat.quickstart.xutils.cache.DiskCacheEntity;
import com.wordplat.quickstart.xutils.cache.LruDiskCache;
import com.wordplat.quickstart.xutils.common.util.TextUtils;
import com.wordplat.quickstart.xutils.http.ProgressHandler;
import com.wordplat.quickstart.xutils.http.RequestParams;
import com.wordplat.quickstart.xutils.http.request.UriRequest;

import java.util.Date;

/**
 * Author: wyouflf
 * Time: 2014/05/26
 *
 * @since 2021-05-09
 */
public abstract class Loader<T> {
    protected ProgressHandler progressHandler;

    /**
     * setParams
     *
     * @param params
     */
    public void setParams(final RequestParams params) {
    }

    public void setProgressHandler(final ProgressHandler callbackHandler) {
        this.progressHandler = callbackHandler;
    }

    /**
     * saveStringCache
     *
     * @param request
     * @param resultStr
     */
    protected void saveStringCache(UriRequest request, String resultStr) {
        saveCacheInternal(request, resultStr, null);
    }

    /**
     * saveByteArrayCache
     *
     * @param request
     * @param resultData
     */
    protected void saveByteArrayCache(UriRequest request, byte[] resultData) {
        saveCacheInternal(request, null, resultData);
    }

    /**
     * newInstance
     *
     * @return Loader
     */
    public abstract Loader<T> newInstance();

    /**
     * load
     *
     * @param request
     * @return T
     * @throws Throwable
     */
    public abstract T load(final UriRequest request) throws Throwable;

    /**
     * loadFromCache
     *
     * @param cacheEntity
     * @return T
     * @throws Throwable
     */
    public abstract T loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable;

    /**
     * save2Cache
     *
     * @param request
     */
    public abstract void save2Cache(final UriRequest request);

    private void saveCacheInternal(UriRequest request, String resultStr, byte[] resultData) {
        if (!TextUtils.isEmpty(resultStr) || (resultData != null && resultData.length > 0)) {
            DiskCacheEntity entity = new DiskCacheEntity();
            entity.setKey(request.getCacheKey());
            entity.setLastAccess(System.currentTimeMillis());
            entity.setEtag(request.getETag());
            entity.setExpires(request.getExpiration());
            entity.setLastModify(new Date(request.getLastModified()));
            entity.setTextContent(resultStr);
            entity.setBytesContent(resultData);
            LruDiskCache.getDiskCache(request.getParams().getCacheDirName()).put(entity);
        }
    }
}
